<?php

namespace App\Listeners;

use App\Constant;
use App\Events\RechargeComplete;
use App\Models\BalanceLogModel;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class CalculateRechargeProfit
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  \App\Events\RechargeComplete  $event
     * @return void
     */
    public function handle(RechargeComplete $event)
    {
        //
        $paylog = $event->paylog;
        $user = $paylog->user;
        $total_deep = $user->deep + 1;
        $upper = $user->upper;
        for ($i=1;$i<=$total_deep;$i++) {
            if(!$upper) {
                break;
            }
            if($i>=4) {
                break;
            }
            BalanceLogModel::create([
                'user_id' => $upper->id,
                'type' => Constant::BALANCE_LOG_TYPE_RECHARGE_PROFIT,
                'value_before' => $upper->balance,
                'value' => ($paylog->money * get_setting('profit_level' . ($i)) / 100),
                'description' => "Recharge Profit",
                'trade_id' => $paylog->relate_id,
            ]);

            $upper->fill([
                'balance' => $upper->balance + ($paylog->money * get_setting('profit_level' . ($i)) / 100)
            ])->save();
            $upper = $upper->upper;
        }

    }
}
